package com.ktgj.flight.service.impl;

import com.alibaba.nacos.shaded.org.checkerframework.checker.units.qual.A;
import com.ktgj.common.core.annotation.Excel;
import com.ktgj.common.core.constant.SalePolicyConstants;
import com.ktgj.common.core.domain.R;
import com.ktgj.common.core.utils.ExcelUtils;
import com.ktgj.common.redis.service.RedisService;
import com.ktgj.customer.api.RemoteCustomerService;
import com.ktgj.customer.api.domain.Employee;
import com.ktgj.file.api.RemoteFilesService;
import com.ktgj.file.api.domain.SysFileApi;
import com.ktgj.flight.domain.Airliner;
import com.ktgj.flight.domain.FlightAdjust;
import com.ktgj.flight.domain.FlightAdjustPassenger;
import com.ktgj.flight.domain.vo.*;
import com.ktgj.flight.mapper.AirlinerMapper;
import com.ktgj.flight.mapper.FlightAdjustMapper;
import com.ktgj.flight.mapper.FlightAdjustPassengerMapper;
import com.ktgj.flight.service.IFlightAdjustService;
import com.ktgj.flight.util.UploadFile;
import com.ktgj.hotel.api.RemoteHotelService;
import com.ktgj.system.api.RemoteFileService;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.SimpleFormatter;

/**
 * 出票渠道调整Service业务层处理
 * 
 * @author ruoyi
 * @date 2021-11-10
 */
@Service
public class FlightAdjustServiceImpl implements IFlightAdjustService
{
    @Autowired
    private FlightAdjustMapper flightAdjustMapper;
    @Autowired
    private AirlinerMapper airlinerMapper;
    @Autowired
    private FlightAdjustPassengerMapper flightAdjustPassengerMapper;
    @Autowired
    private RemoteCustomerService remoteCustomerService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private RemoteHotelService remoteHotelService;

    /**
     * 查询出票渠道调整
     * 
     * @param adjustId 出票渠道调整ID
     * @return 出票渠道调整
     */
    @Override
    public FlightAdjust selectFlightAdjustById(Integer adjustId)
    {
        return flightAdjustMapper.selectFlightAdjustById(adjustId);
    }

    /**
     * 查询出票渠道调整列表
     * 
     * @param flightAdjust 出票渠道调整
     * @return 出票渠道调整
     */
    @Override
    public List<FlightAdjust> selectFlightAdjustList(FlightAdjust flightAdjust)
    {
        return flightAdjustMapper.selectFlightAdjustList(flightAdjust);
    }

    /**
     * 新增出票渠道调整
     * 
     * @param flightAdjust 出票渠道调整
     * @return 结果
     */
    @Override
    public int insertFlightAdjust(FlightAdjust flightAdjust)
    {
        return flightAdjustMapper.insertFlightAdjust(flightAdjust);
    }

    /**
     * 修改出票渠道调整
     * 
     * @param flightAdjust 出票渠道调整
     * @return 结果
     */
    @Override
    public int updateFlightAdjust(FlightAdjust flightAdjust)
    {
        return flightAdjustMapper.updateFlightAdjust(flightAdjust);
    }

    /**
     * 批量删除出票渠道调整
     * 
     * @param adjustIds 需要删除的出票渠道调整ID
     * @return 结果
     */
    @Override
    public int deleteFlightAdjustByIds(Integer[] adjustIds)
    {
        return flightAdjustMapper.deleteFlightAdjustByIds(adjustIds);
    }

    /**
     * 删除出票渠道调整信息
     * 
     * @param adjustId 出票渠道调整ID
     * @return 结果
     */
    @Override
    public int deleteFlightAdjustById(Integer adjustId)
    {
        return flightAdjustMapper.deleteFlightAdjustById(adjustId);
    }

    /**
     * 根据航司二字码和身份证号关联查询大客户信息
     * @param airCode 航司二字码
     * @param cardId 身份证号
     * @return
     */
    @Override
    public FlightAdjust getFlightAdjustByAirCodeAndCardId(String airCode, String cardId) {
        return flightAdjustMapper.getFlightAdjustByAirCodeAndCardId(airCode,cardId);
    }

    /**
     * 渠道调整列表
     * */
    @Override
    public List<FlightAdjust> flightAdjustList(FlightAdjustVo flightAdjustVo) {
        List<FlightAdjust> flightAdjusts = flightAdjustMapper.flightAdjustList(flightAdjustVo);

        if (flightAdjusts.size() > 0){
            for (FlightAdjust flightAdjust : flightAdjusts) {
                Airliner airliner = airlinerMapper.selectName(flightAdjust.getAirlinerId());
                if (airliner != null){
                    flightAdjust.setAirlinerId(airliner.getAirliner());
                }
                else {
                    flightAdjust.setAirlinerId("");
                }

                if (flightAdjust.getTicketingChannel() != null){
                    if (flightAdjust.getTicketingChannel().equals(SalePolicyConstants.B2B.getValue())){
                        flightAdjust.setTicketingChannel("B2B");
                    }
                    else if (flightAdjust.getTicketingChannel().equals(SalePolicyConstants.BSP.getValue())){
                        flightAdjust.setTicketingChannel("BSP");
                    }
                    else if (flightAdjust.getTicketingChannel().equals(SalePolicyConstants.OtherBuy.getValue())){
                        flightAdjust.setTicketingChannel("外购");
                    }
                    else if (flightAdjust.getTicketingChannel().equals(SalePolicyConstants.LinkAirline.getValue())){
                        flightAdjust.setTicketingChannel("航空直连");
                    }
                    else if (flightAdjust.getTicketingChannel().equals(SalePolicyConstants.Agreement.getValue())){
                        flightAdjust.setTicketingChannel("三方协议");
                    }
                    else if (flightAdjust.getTicketingChannel().equals(SalePolicyConstants.SelfSurpport.getValue())){
                        flightAdjust.setTicketingChannel("自营");
                    }
                }
            }
        }
        return flightAdjusts;
    }

    /**
     * 新增渠道调整
     * */
    @Override
    public int addFlightAdjust(HttpServletRequest request, FlightAdjust flightAdjust) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String token = request.getHeader("token");
        R<Employee> loginEmployeeByToken = remoteCustomerService.getLoginEmployeeByToken(token);
        if (loginEmployeeByToken.getData() == null){
            throw new Exception(loginEmployeeByToken.getMsg());
        }

        Date date = new Date();
        flightAdjust.setCreateTime(date);
        flightAdjust.setEmployeeid(Integer.parseInt(loginEmployeeByToken.getData().getEmployeeId().toString()));
        if (flightAdjust.getFlightdateSetOff() != null && flightAdjust.getFlightdateBack() != null){
            flightAdjust.setFlightdate(flightAdjust.getFlightdateSetOff() + "|" + flightAdjust.getFlightdateBack());
        }

        if (flightAdjust.getTmpStarttime() != null){
            flightAdjust.setStarttime(format.parse(flightAdjust.getTmpStarttime()));
        }
        if (flightAdjust.getTmpEndtime() != null){
            flightAdjust.setEndtime(format.parse(flightAdjust.getTmpEndtime()));
        }
        if (flightAdjust.getTmpOperationtime() != null){
            flightAdjust.setOperationtime(format.parse(flightAdjust.getTmpOperationtime()));
        }

        if (flightAdjust.getDeliverytypeList().size() > 0){
            for (int i = 0 ; i < flightAdjust.getDeliverytypeList().size() ; i++){
                if (i == 0){
                    flightAdjust.setDeliverytype(flightAdjust.getDeliverytypeList().get(i));
                }
                else {
                    flightAdjust.setDeliverytype(flightAdjust.getDeliverytype() + "|" +flightAdjust.getDeliverytypeList().get(i));
                }
            }
        }

        if (flightAdjust.getOrdersorceList().size() > 0){
            for (int i = 0 ; i < flightAdjust.getOrdersorceList().size() ; i++){
                if (i == 0){
                    flightAdjust.setOrdersorce(flightAdjust.getOrdersorceList().get(i));
                }
                else {
                    flightAdjust.setOrdersorce(flightAdjust.getOrdersorce() + "|" +flightAdjust.getOrdersorceList().get(i));
                }
            }
        }
        int i = flightAdjustMapper.insertFlightAdjust(flightAdjust);

        if (flightAdjust.getFlightAdjustPassengerList().size() > 0){
            for (FlightAdjustPassenger flightAdjustPassenger : flightAdjust.getFlightAdjustPassengerList()) {
                flightAdjustPassenger.setAdjustId(Long.valueOf(flightAdjust.getAdjustId()));
                flightAdjustPassenger.setCreateTime(date);
                flightAdjustPassenger.setStatusType(1l);
                flightAdjustPassenger.setEmployeeId(loginEmployeeByToken.getData().getEmployeeId().toString());
                flightAdjustPassenger.setOperateTime(date);
                int passenger = flightAdjustPassengerMapper.insertFlightAdjustPassenger(flightAdjustPassenger);
                if (passenger <= 0){
                    throw new Exception("添加白名单" + flightAdjustPassenger.getName() + "失败");
                }
            }
        }
        return i;
    }

    /**
     * 上传文件到服务器并反填
     * */
    @Override
    public List<FlightAdjustPassengerVo> flightAdjustPassengerVo(MultipartFile file) throws Exception {
        List<FlightAdjustPassengerVo> flightAdjustPassengerVoList = new ArrayList<>();
        ExcelUtils excelUtils = new ExcelUtils();
        UploadFile uploadFile = new UploadFile();

        List<FlightAdjustPassengerVo> flightAdjustPassengerVos = null;

        //上传文件到服务器
        DocumentVo document = uploadFile.document(file);

        //创建锁
        boolean lock = redisService.lock(document.getUrl(), 1, 30);

        File[] tmpFile = document.getFile().listFiles();

        if (!lock){
            throw new Exception("接口被占用，请稍后重试");
        }

        try {
            Workbook workbook = excelUtils.getWorkbookFromExcel(tmpFile[0]);

            List<List<Object>> lstExcelObjs = excelUtils.readExcel(workbook,0);

            List<CountVo> countVoList = new ArrayList<>();

            for (int i = 0 ; i < lstExcelObjs.size() ; i++){
                //获取表格头
                if (i == 0){
                    for (int j = 0 ; j < lstExcelObjs.get(i).size() ; j++){
                        CountVo countVo = new CountVo();
                        countVo.id = j;
                        countVo.name = lstExcelObjs.get(i).get(j).toString();
                        countVoList.add(countVo);
                    }
                }

                FlightAdjustPassengerVo flightAdjustPassengerVo = new FlightAdjustPassengerVo();
                //获取数据
                for (int j = 0 ; j < lstExcelObjs.get(i).size() ; j++){
                    if (i != 0){
                        if (j % 2 == 0){
                            flightAdjustPassengerVo.setName(lstExcelObjs.get(i).get(j).toString());
                        }
                        else if (j % 2 != 0){
                            flightAdjustPassengerVo.setCardId(lstExcelObjs.get(i).get(j).toString());
                        }
                        flightAdjustPassengerVoList.add(flightAdjustPassengerVo);
                    }
                }
            }

            flightAdjustPassengerVos = new ArrayList<>();
            for (FlightAdjustPassengerVo flightAdjustPassengerVo : flightAdjustPassengerVoList) {
                if (!flightAdjustPassengerVos.contains(flightAdjustPassengerVo)){
                    flightAdjustPassengerVos.add(flightAdjustPassengerVo);
                }
            }
        } catch (Exception e){
            throw new Exception("上传失败");
        }
        finally {
            //删除文件
            File delFile = new File(document.getUrl());
            delFile.delete();
            //销毁锁
            redisService.deleteLock(document.getUrl());
        }

        return flightAdjustPassengerVos;
    }

    /**
     * 查询待修改的渠道调整信息
     * */
    @Override
    public AdjustPassengerVo selectAdjustPassengerVo(Long id) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        AdjustPassengerVo adjustPassengerVo = new AdjustPassengerVo();
        FlightAdjust flightAdjust = flightAdjustMapper.selectAdjustPassengerVo(id);

        if (flightAdjust.getAdjustId() != null){
            adjustPassengerVo.setAdjustId(Long.valueOf(flightAdjust.getAdjustId()));
        }
        adjustPassengerVo.setDeparture(flightAdjust.getDeparture());
        adjustPassengerVo.setArrival(flightAdjust.getArrival());
        adjustPassengerVo.setAirlinerId(flightAdjust.getAirlinerId());

        Airliner airliner = airlinerMapper.selectName(flightAdjust.getAirlinerId());
        adjustPassengerVo.setAirlinerName(airliner.getAirliner());
        adjustPassengerVo.setTicketingCChannel(flightAdjust.getTicketingChannel());
        adjustPassengerVo.setCabin(flightAdjust.getCabin());

        if (flightAdjust.getStarttime() != null){
            adjustPassengerVo.setStartTime(format.format(flightAdjust.getStarttime()));
        }

        if (flightAdjust.getEndtime() != null){
            adjustPassengerVo.setEndTime(format.format(flightAdjust.getEndtime()));
        }

        List<String> orderSorce = new ArrayList<>();
        if (flightAdjust.getOrdersorce() != null){
            if (flightAdjust.getOrdersorce().indexOf("|") == -1){
                orderSorce.add(flightAdjust.getOrdersorce());
            }
            else {
                String[] ordersorces = flightAdjust.getOrdersorce().split("|");

                for (int i = 0 ; i < ordersorces.length ; i++){
                    if (!ordersorces[i].equals("|")){
                        orderSorce.add(ordersorces[i]);
                    }
                }
            }
        }
        adjustPassengerVo.setOrderSorce(orderSorce);

        List<String> deliceryType = new ArrayList<>();
        if (flightAdjust.getDeliverytype() != null){
            if (flightAdjust.getDeliverytype().indexOf("|") == -1){
                deliceryType.add(flightAdjust.getDeliverytype());
            }
            else {
                String[] deliceryTypes = flightAdjust.getDeliverytype().split("|");
                for (int i = 0 ; i < deliceryTypes.length ; i++){
                    if (!deliceryTypes[i].equals("|")){
                        deliceryType.add(deliceryTypes[i]);
                    }
                }
            }
        }
        adjustPassengerVo.setDeliceryType(deliceryType);

        adjustPassengerVo.setBigCustomer(flightAdjust.getBigcustomer());

        if (flightAdjust.getFlightdate() != null){
            int i = flightAdjust.getFlightdate().indexOf("|");
            adjustPassengerVo.setFlightdateSetOff(flightAdjust.getFlightdate().substring(0, i));
            adjustPassengerVo.setFlightdateBack(flightAdjust.getFlightdate().substring(i + 1));
        }

        adjustPassengerVo.setFlightNo(flightAdjust.getFlightno());
        adjustPassengerVo.setIsCheckInfo(flightAdjust.getIscheckinfo().toString());
        adjustPassengerVo.setIssDesc(flightAdjust.getIssDesc());
        adjustPassengerVo.setFitGuest(flightAdjust.getFitGuest().toString());
        adjustPassengerVo.setVIPPolicyType(flightAdjust.getVipPolicyType().toString());
        adjustPassengerVo.setVipPolicyAmount(flightAdjust.getVipPolicyAmount());

        List<String> cpMark = new ArrayList<>();
        if (flightAdjust.getCpMark() != null){
            if (flightAdjust.getCpMark().indexOf("|") == -1){
                cpMark.add(flightAdjust.getCpMark());
            }
            else {
                String[] cpMarks = flightAdjust.getCpMark().split("|");
                for (int i = 0 ; i < cpMarks.length ; i++){
                    if (!cpMarks[i].equals("|")){
                        cpMark.add(cpMarks[i]);
                    }
                }
            }
        }
        adjustPassengerVo.setCpMark(cpMark);
        adjustPassengerVo.setPATMark(flightAdjust.getPatMark());
        return adjustPassengerVo;
    }

    /**
     * 修改渠道调整信息
     * */
    @Transactional
    @Override
    public int updateAdjustPassengerVo(HttpServletRequest request, FlightAdjust flightAdjust) throws Exception {
        Date date = new Date();
        if (flightAdjust.getFlightdateSetOff() != null && flightAdjust.getFlightdateBack() != null){
            flightAdjust.setFlightdate(flightAdjust.getFlightdateSetOff() + "|" + flightAdjust.getFlightdateBack());
        }
        String token = request.getHeader("token");
        R<Employee> loginEmployeeByToken = remoteCustomerService.getLoginEmployeeByToken(token);
        if (loginEmployeeByToken.getData() != null){
            flightAdjust.setCreateTime(date);
            flightAdjust.setEmployeeid(Integer.parseInt(loginEmployeeByToken.getData().getEmployeeId().toString()));
            int i = flightAdjustMapper.updateFlightAdjust(flightAdjust);
            if (i > 0){
                return i;
            }
            else {
                throw new Exception("修改渠道调整信息失败");
            }
        }
        else {
            throw new Exception(loginEmployeeByToken.getMsg());
        }
    }

    /**
     * 删除渠道调整信息及附属大客户信息
     * */
    @Transactional
    @Override
    public int delAdjustPassengerVo(Long id) throws Exception {
        int i = flightAdjustMapper.deleteFlightAdjustById(Integer.parseInt(id.toString()));
        if (i > 0){
            int passenger = flightAdjustPassengerMapper.delFlightAdjustPassenger(id);
            if (passenger > 0){
                return passenger;
            }
            else {
                throw new Exception("删除信息失败");
            }
        }
        else {
            throw new Exception("删除失败");
        }
    }
}
